<?php


namespace App\Repositories\Policy\Eloquent;


use App\Repositories\Policy\Contracts\TcOrderInterface;
use Curl\StrService\StrService;
use Illuminate\Support\Facades\Cache;

class TcOrderRepository extends TcRepository implements TcOrderInterface
{

    public function token()
    {

        $access_token = Cache::get('tc_access_token');
        if (!$access_token) {

            $time = time();

            $url = '/openapi/create/accesstoken?t='.$time;

            $param = [
                'app_id'    => $this->app_id,
                'app_key'   => $this->app_key
            ];

            $this->header = [
                'Content-Type:application/json',
                'x-tg-token:'.$time,
                'x-tg-sign:'.$this->sign($url,$param,$time),
            ];

            $res = $this->orderReq($url,$param);
            if ($res && !empty($res['access_token'])) {

                $access_token = $res['access_token'];
                Cache::put('tc_access_token',$res['access_token'],119);
            }
        }

        return $access_token;
    }

    /**
     * 订单详情
     * @param $orderNo
     * @return mixed|void
     */
    public function orderInfo($orderNo)
    {

        $time = time();
        $url = '/SupplierOrder/GetOrderDetail?t='.$time;

        $param = [
            'orderSerialNo'     => $orderNo,
            'requestGuid'       => StrService::uuid(),
        ];

        $this->header = [
            'Content-Type:application/json',
            'x-tg-token:'.$this->token(),
            'x-tg-sign:'.$this->sign($url,$param,$this->token()),
            'x-appkey:'.$this->app_key
        ];

        $res = $this->orderReq($url,$param);
        if ($res && !empty($res['data']) && isset($res['isSuccess']) && $res['isSuccess'] == true) {

            return $res['data'];
        }

        return false;
    }

    /**
     * sign签名方式
     * @param $url
     * @param $body
     * @param $time
     * @return string
     */
    private function sign($url,$body,$time){


        $body = json_encode($body);
        $hashKey = $this->app_secret.$time;
        return hash_hmac('sha256',$url.$body,$hashKey);
    }
}